<template>
  <div class="modal">
    <el-dialog
      v-model="dialogVisible"
      :title="isNewRef ? '新建部门' : '编辑部门'"
      width="500"
      center
    >
      <div class="form">
        <el-form size="large" :model="formData" label-width="80px">
          <el-form-item label="部门名字" prop="name">
            <el-input v-model="formData.name" placeholder="请输入"></el-input>
          </el-form-item>
        </el-form>
        <el-form size="large" :model="formData" label-width="80px">
          <el-form-item label="部门领导" prop="leader">
            <el-input v-model="formData.leader" placeholder="请输入"></el-input>
          </el-form-item>
        </el-form>

        <el-form size="large" :model="formData" label-width="80px">
          <el-form-item label="选择部门" prop="parentId">
            <el-select v-model="formData.parentId" placeholder="请选择">
              <template v-for="item in entireDepartments" :key="item.id">
                <el-option :label="item.name" :value="item.id"></el-option>
              </template>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { storeToRefs } from 'pinia'
import useMainStore from '@/store/main/main'
import useSystemStore from '@/store/main/system/system'
const formData = reactive<any>({
  name: '',
  leader: '',
  parentId: ''
})
//用于传递函数参数，要编辑数据的id，新建时没有，编辑时有
const editData = ref()
//新建还是编辑状态，true为新建,false为编辑
const isNewRef = ref(true)
//获取角色数据
const mainStore = useMainStore()
const systemStore = useSystemStore()
const { entireDepartments } = storeToRefs(mainStore)
//表示一开始是否可见,参数区分是新建还是编辑
const dialogVisible = ref(false)

function setModalVisible(isNew: boolean = true, itemData: any) {
  dialogVisible.value = true
  isNewRef.value = isNew
  //编辑状态下
  if (!isNew && itemData) {
    for (const key in formData) {
      formData[key] = itemData[key]
    }
    editData.value = itemData
  } else {
    //新建状态下清空表单数据，防止在编辑之后点击新建后又保留了之前的表单数据
    for (const key in formData) {
      formData[key] = ''
    }
    editData.value = null
  }
}
function handleConfirmClick() {
  dialogVisible.value = false
  if (!isNewRef.value && editData.value) {
    console.log('编辑状态')
    //编辑状态确定按钮点击事件
    systemStore.editPageDataAction('department', editData.value.id, formData)
    //新建状态确定按钮点击事件
  } else {
    console.log('新建状态')

    systemStore.newPageDataAction('department', formData)
  }
}
defineExpose({ setModalVisible })
</script>

<style lang="less" scoped>
</style>